#!/usr/bin/env python
# -*- coding: utf-8 -*-

from google.appengine.ext import webapp
from google.appengine.api import urlfetch
from google.appengine.ext.webapp import template

from BeautifulSoup import BeautifulSoup
import urllib
import os
import GetMp3Links

from google.appengine.api.urlfetch import DownloadError
from HTMLParser import HTMLParseError

class ScrollTistoryMp3ListPage(webapp.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/html;charset=UTF-8'
        
        origQuery = self.request.get('query').encode('utf-8')
        if origQuery == '':
            hasQuery = False
        else:
            hasQuery = True
            query = origQuery + ' mp3 site:tistory.com'
            query = query.replace(' ', '+')
            
        start = self.request.get('start').encode('utf-8')
        if start == '':
            start = 0
        else:
            start = int(start)
        end = 15
        
        blogUrls = []
        search_result = ''
        mp3Links = []
                    
        num = 1
        if hasQuery:            
            searchUrl = 'http://www.google.co.kr/search?q=' + urllib.quote(query) + '&start=' + str(start) + '&num=' + str(end) + '&sa=N'
            result = urlfetch.fetch( searchUrl )
            if result.status_code == 200:
                soup  = BeautifulSoup( unicode(result.content, 'cp949' ).encode('utf-8') )
                items = soup('li')
                for item in items:
                    links = item.findAll(name='a', attrs={'class': 'l'})
                    for link in links:
                        href_attr = link['href']  
                        href_attr = href_attr[ href_attr.find('http://'): ]
                        blogUrls.append( {'blogUrl': href_attr, 'num': num} )
                        num += 1
        try:
            blogUrl = blogUrls[0]
        except:
            blogUrl = ''
            
        template_values = {
                           'hasQuery': hasQuery,
                           'origQuery': origQuery,
                           'start': start,
                           'end': num - 1,
                           'blogUrls': blogUrls,
                           'search_results': search_result,
                          }
        
        path = os.path.join(os.path.dirname(__file__), 'html/ScrollTistoryMp3ListPage.html')
        self.response.out.write(template.render(path, template_values))
        
        
class TistoryMp3List(webapp.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/html;charset=UTF-8'
        
        blogUrl = self.request.get('blogUrl').encode('utf-8')
        num = self.request.get('num').encode('utf-8')
        if num != '':
            num = int(num)
        else:
            num = 0
            
        title = ''
        urls = []
            
        try:
            mobileUrl, title = GetMp3Links.getMobileUrlsFromTistory( blogUrl )
            mp3Links = GetMp3Links.getMp3LinksFromMobileUrls( mobileUrl )
            urls += mp3Links
        except HTMLParseError:
            pass
        except DownloadError:
            pass
        except:
            pass
        
        template_values = {
                           'blogUrl': blogUrl,
                           'title': title,
                           'urls': urls,
                           'num': num,
                          }
        
        path = os.path.join(os.path.dirname(__file__), 'html/TistoryMp3List.html')
        self.response.out.write(template.render(path, template_values))
        
# EOF